﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Agr.CQRS.Infrastructure.ServiceBus;
using Agr.CQRS.Domain.Commands;
using log4net;

namespace Agr.CQRS.Infrastructure.Commands
{
    public class CommandRouter
    {
        private static ILog Logger = LogManager.GetLogger(typeof(CommandIssuer));

        private IServiceBus servicebus;
        private CommandHandlerFactory factory;

        public CommandRouter(IServiceBus sb, CommandHandlerFactory chf)
        {
            factory = chf;
            servicebus = sb;
        }

        private void routeNewCommand(Command cmd)
        {
            Logger.InfoFormat("Received command {0}", cmd.ToString());

            try
            {
                var handler = factory.CreateCommandHandlerFor(cmd);
                handler.ExecuteCommand(cmd);
            }
            catch (Exception ex)
            {
                Logger.Error(string.Format("Command execution failed for {0}", cmd.ToString()), ex);
                servicebus.Publish(new CommandFailedEvent { Exception = ex });
            }
        }

        public void Start()
        {
            Logger.Warn("CommandRouter started");

            servicebus.Subscribe<Command>(routeNewCommand);
        }
    }

}
